from app.admin import admin
from flask import request, render_template, redirect, jsonify, current_app, flash, url_for
from flask_login import login_user
from hashlib import md5
from models.models import User
from app import db

@admin.route('/login',methods=['GET','POST'])
def login():
    if request.method == 'POST':
        name = request.form.get('username')         # 获取用户名
        password = request.form.get('password')     # 获取密码
        user = User.query.filter_by(username=name).first()
        if user:
            password = md5((password + current_app.config['SECRET_KEY']).encode('utf-8')).hexdigest()   # 密码加密判断
            if user.password_hash==password:
                login_user(user)
                return redirect(url_for('admin.index'))     # 通过跳转后台界面
            else:
                flash("密码错误")   # 失败返回失败信息
        else:
            flash("用户不存在")
    return render_template('game/login.html',title='登陆',msg='没有账号？',operate='点击注册',
                           url='./register',btn='登陆',to_login=True,post_url='./login')

@admin.route('/register',methods=['GET','POST'])
def register():
    if request.method == 'POST':
        name = request.form.get('username')
        key = request.form.get('key') # 获取密钥
        password = request.form.get('password')
        if key != current_app.config['SECRET_KEY']: # 密钥判断
            flash('您无权注册')
        else:
            password = md5((password+key).encode('utf-8')).hexdigest()
            obj = User(username=name,password_hash=password)
            db.session.add(obj)
            db.session.commit()
            login_user(obj)
            return redirect(url_for('admin.index'))
    return render_template('game/login.html',title='注册',msg='已有账号',operate='点击登陆',
                           url='./login',btn='注册',to_login=False,post_url='./register')